<html>
  <head>
        <title>Bike Trails!</title>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map { height: 100% }
        #TextArea1
        {
            height: 95px;
            width: 172px;
        }
    </style>
    <script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDtAJD6yDB6D-AcxMQohCKDRFkMiVSM56c&sensor=true&libraries=geometry,panoramio">
    </script>
    <script type="text/javascript" src="GPXParser.js"></script>
    <script src="json2.js"></script>
	<script src="process.php"></script>
    <script type="text/javascript">
    	var data = {};
        var poly, map;
        var markers = [];
        var trailPath = new google.maps.MVCArray; //Model View Controller

        var rendererOptions = {draggable: true};
        var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        var directionsService2 = new google.maps.DirectionsService();

        function initialize() {
        // set up all the options for the map
        var Fargo = new google.maps.LatLng(46.877186,-96.789803);
        var myOptions = {
          center: Fargo,
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // create a map
        map = new google.maps.Map(document.getElementById("map"),
            myOptions);

        ////Upload GPX file to the map
        var xmlrequest = window.ActiveXObject ?
        	new ActiveXObject('Microsoft.XMLHTTP') :
        	new XMLHttpRequest();
        xmlrequest.open("GET","valley.gpx",true);
        xmlrequest.onreadystatechange = function()
        {   // when the xml is loaded completely
        	if(xmlrequest.readyState == 4)
        	{
        		xmlDOC = xmlrequest.responseXML;
        		parser = new GPXParser(xmlDOC, map);
        		parser.SetTrackColour("#ff00ff");    // set the color of the track
        		parser.SetTrackWidth(5);             // set the track width
        		parser.SetMinTrackPointDelta(0.001); // Set the minimum distance between trackpoints.
        		parser.AddTrackpointsToMap();        // add all the track points to the map
        		parser.AddWaypointsToMap();          // add all the way points to the map
        	}
        }
        xmlrequest.send();
        //////////////////////////////////////////////
        // set up the two directionsService
        var directionsService = new google.maps.DirectionsService();
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById("directionsPanel"));
        // if the route has been changed, then update the route
        google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){
            updateRoute(directionsDisplay.directions);
        });

        google.maps.event.addListener(map, 'click', function(event) {
                // capture the point clicked on the map
            var request = {
                origin:event.latLng,
                destination:event.latLng,
                travelMode: google.maps.DirectionsTravelMode.BICYCLING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    // find the on-street marker closest to the clicked point on the map
                    var marker = new google.maps.Marker({
                        position: response.routes[0].legs[0].start_location,
                        map: null
                    });
                    // add the marker to the markers array
                    markers.push(marker);

                    // remove the marker when it is clicked
                    google.maps.event.addListener(marker, 'click', function(){
                        marker.setMap(null);  // remove the marker from the map
                        // find index of the marker being moved inside the markers array
                        for(var i=0, I=markers.length; i < I && markers[i] != marker; i++);
                        markers.splice(i,1);  // remove the ith element inside markers
                    });
                    // if the markers' length is longer than 1, remove all the markers from the map
                    if(markers.length>1)
                    {
                        calcRoute();
                        removeMarkers();
                    }
                    else // if there's only one marker, then display that one
                    {
                        markers[0].setMap(map);
                    }
                }
            });

        });

        }// initialize

        // call calcRoute only if markers.length > 1
        function calcRoute()
        {
                var waypts = [];
                // store the points(excluding start, end points) from markers array to waypts
                for(var i=1; i<markers.length-1 && markers.length>2; i++)
                {
                    waypts.push({
                        location: markers[i].getPosition(),
                        stopover: true
                    });
                }
                // set up the request for directionsService2, and set waypoints for stopovers
                var request = {
                    origin: markers[0].getPosition(),
                    destination: markers[markers.length-1].getPosition(),
                    waypoints: waypts,
                    travelMode: google.maps.TravelMode.BICYCLING
                };

                //display directionsService2
                directionsService2.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                    }
                });
        }// calcRoute

        function test()
        {
            document.write('Hello World!');
        }// test


        function removeMarkers()
        {
            for(var i=0; i<markers.length; i++)
            {
                markers[i].setMap(null);
            }
        }// remove all the markers from the map

        function deleteMarkers()
        {
            var size = markers.length;
            for(var i=0; i<size; i++)
            {
                markers.splice(0,1);
            }
        }// delete all the elements inside array markers

        function updateRoute(result)
        {
            var total = 0;
            var myroute = result.routes[0];
            // the starting location
            var marker = new google.maps.Marker({
                    position: myroute.legs[0].start_location,
                    map: null
            });
            // delete all the markers
            deleteMarkers();
            // add the starting point
            markers.push(marker);
            for (i = 0; i < myroute.legs.length; i++) {
                total += myroute.legs[i].distance.value;

                // add all the way pionts for each leg
                for(j=0; j<myroute.legs[i].via_waypoints.length; j++)
                {
                	var marker = new google.maps.Marker({
                        position: myroute.legs[i].via_waypoints[j],
	                    map: null
                	});
                	// add via waypoints between each leg to the markers array
                	markers.push(marker);
                }
                // add all the legs to the markers
                var marker = new google.maps.Marker({
                    position: myroute.legs[i].end_location,
                    map: null
                });
                markers.push(marker);

            }
            total = total / 1000.
            document.getElementById("total").innerHTML = total + " km";
        }// update the route once it has been changed

        function save_waypoints()
		{

		var description=document.getElementById("description").value;
		var index=document.getElementById("routeTypeSel").selectedIndex;
		var routes=document.getElementById("routeTypeSel").options;
		routeType=routes[index].text;

	if(description.length > 0)
	{
		    document.getElementById("total").innerHTML = total + " km";
			var w=[];
			data.start = {'lat': markers[0].getPosition().lat(), 'lng': markers[0].getPosition().lng()};
			data.end = {'lat': markers[markers.length-1].getPosition().lat(), 'lng': markers[markers.length-1].getPosition().lng()};
			if(markers.length>2)
			{
				var size = markers.length-2;
				for(var i=0;i<size;i++) w[i] = [markers[i+1].getPosition().lat(),markers[i+1].getPosition().lng()];
			}

			data.waypoints = w;
			//alert(data.waypoints[0]);

			var str = JSON.stringify(data);

			var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
			jax.open('POST','process.php');
			jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			jax.send('command=save&mapdata='+str+'&routeType='+routeType+'&description='+description);
			jax.onreadystatechange = function(){ if(jax.readyState==4) {
				if(jax.responseText.indexOf('bien')+1)
					alert(jax.responseText);
				else
					alert("Route Saved");

			}}

		}
		else
		{
		alert("Please write somthing about the route!");

		}

		}// save the route to the data base

    </script>

  </head>
  <body onload="initialize()">

      <table style="width: 100%; height:100%">
          <tr>
              <td style="width:80%">
                <div id="map" style="float:left;width:100%; height:100%"></div>
              </td>
              <td style="width: 20%; vertical-align:top">
                  <div style="width:100%; text-align:center; margin:0px auto 0px auto; margin-top:10px;">
	                  <br />
	                <input type="button" value="Save Route" onClick="save_waypoints()"><br />
                      <br />
                      Route Type:<br />
                        &nbsp;<select id="routeTypeSel" name="routeType">
                            <option selected="selected" label="Offroad" value="Offroad">Offroad</option>
                            <option label="Touring" value="Touring">Touring</option>
                            <option label="Casual" value="Casual">Casual</option>
                        </select>
                      <br />
                      <br />
                      Route Description:*<br />
                      <textarea id="description" style="width:95%" name="S1"></textarea>
                      <p>
					                       <p>
                      <form enctype="multipart/form-data" action="uploader.php" method="POST">


					  <br/>Please choose a file: <input name="uploadedfile" type="file" /><br />
                      <input type="submit" value="Upload" />

					  </form>
					  </p>
					  </p>

					  <p>Total Distance: <span id="total"></span></p>
                    <div id="directionsPanel" style="float:right;width:100%;height 100%"></div>
                </div>

              </td>

          </tr>
      </table>


  </body>
</html>
